﻿using HY.Common;
using HY.Model;
using HY.Service;
using SqlSugar;
#pragma warning disable IDE0019
namespace HY.Web
{
    public class GlobalClass
    {
        public static List<SysRole> GetSysRoleList()
        {
            List<SysRole> roleList = CacheHelper.Get(SystemConst.CacheKey.SysRole) as List<SysRole>;
            if (roleList == null)
            {
                roleList = DbContext.db.Queryable<SysRole>().OrderBy(o => o.Id, OrderByType.Desc).ToList();
                CacheHelper.Set_SlidingExpire(SystemConst.CacheKey.SysRole, roleList, TimeSpan.FromMinutes(AppSetting.GetValue<double>(SystemConst.CacheKey.SlidingMinutes, 30)));
            }
            return roleList;
        }

        public static List<SysResource> GetSysResourceList()
        {
            List<SysResource> resourceList = CacheHelper.Get(SystemConst.CacheKey.SysResource) as List<SysResource>;
            if (resourceList == null)
            {
                resourceList = DbContext.db.Queryable<SysResource>().OrderBy(o => o.SortNumber).ToList();
                CacheHelper.Set_SlidingExpire(SystemConst.CacheKey.SysResource, resourceList, TimeSpan.FromMinutes(AppSetting.GetValue<double>(SystemConst.CacheKey.SlidingMinutes, 30)));
            }
            return resourceList;
        }

        /// <summary>
        /// 角色鉴权
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="roleId"></param>
        /// <param name="authUrl"></param>
        /// <returns></returns>
        public static bool AuthCheck(string userName, string roleId, string authUrl)
        {
            if (roleId == "0" && (userName == "admin" || userName == "gaoqh")) return true;
            //开始鉴权
            long menuId = GetSysResourceList()?.FirstOrDefault(p => p.ResourceUrl?.TrimStart('/').Equals(authUrl, StringComparison.CurrentCultureIgnoreCase) ?? false)?.Id ?? 0;
            SysRole currRole = GetSysRoleList()?.FirstOrDefault(r => r.Id.ToString() == roleId);
            if (currRole != null && ("," + currRole.ResourceIds + ",").Contains("," + menuId + ","))
                return true;
            return false;
        }
    }
}
#pragma warning restore IDE0019